# This file contains the fastlane.tools configuration
# You can find the documentation at https://docs.fastlane.tools
#
# For a list of all available actions, check out
#
#     https://docs.fastlane.tools/actions
#
# For a list of all available plugins, check out
#
#     https://docs.fastlane.tools/plugins/available-plugins
#

# Uncomment the line if you want fastlane to automatically update itself
# update_fastlane

default_platform(:ios)

desc 'Build, Archive, and Upload to ASC'
lane :release do |options|
  is_nightly = options[:nightly].to_i > 0

  xcversion(version: '13.3')

  app_identifier = ENV['APP_IDENTIFIER']
  scheme = ENV['SCHEME']
  configuration = 'App Store Release'

  app_store_connect_api_key

  # Signal provisioning
  sigh(
    app_identifier: app_identifier,
    template_name: 'Unrestricted PushKit entitlement for iOS 13 U68MSDN6DR (Dist)'
  )
  update_project_provisioning(
    target_filter: "^Signal$",
    build_configuration: configuration,
    profile: "./AppStore_#{app_identifier}.mobileprovision"
  )

  # NSE provisioning
  sigh(
    app_identifier: "#{app_identifier}.SignalNSE",
    template_name: 'Notification Service Extension Filtering iOS (Dist)'
  )
  update_project_provisioning(
    target_filter: "^SignalNSE$",
    build_configuration: configuration,
    profile: "./AppStore_#{app_identifier}.SignalNSE.mobileprovision"
  )

  # SAE Provisioning
  sigh(
    app_identifier: "#{app_identifier}.shareextension",
    template_name: 'Unrestricted PushKit entitlement for iOS 13 U68MSDN6DR (Dist)'
  )
  update_project_provisioning(
    target_filter: "^SignalShareExtension$",
    build_configuration: configuration,
    profile: "./AppStore_#{app_identifier}.shareextension.mobileprovision"
  )

  gym(
    workspace: 'Signal.xcworkspace',
    scheme: scheme,
    configuration: configuration,
    clean: true,
    derived_data_path: './build',
    xcargs: "WARNING_CFLAGS='$(inherited) -Wno-everything'"
  )

  # Transporter only allows uploading one instance of
  # an app at a time. To workaround and allow parallel
  # building we need to wait for the transporter lock
  # to be released.
  puts "\e[33mWaiting for transporter lock, this could take a while...\e[0m"
  lock = File.open("#{Dir.home}/.fastlane.transporter.lock", File::CREAT)
  lock.flock(File::LOCK_EX)
  puts "\e[32mTransporter lock acquired!\e[0m"

  if is_nightly
    upload_to_testflight(
      app_identifier: app_identifier,
      ipa: './Signal.ipa',
      changelog: "nightly-#{Time.now.strftime('%m-%d-%Y')}",
      notify_external_testers: true,
      distribute_external: true,
      groups: %w(Internal QA)
    )
  else
    upload_to_testflight(
      app_identifier: app_identifier,
      skip_submission: true,
      skip_waiting_for_build_processing: true,
      ipa: './Signal.ipa'
    )
  end

  lock.flock(File::LOCK_UN)
  lock.close
end
